package cn.yunbamboos.mybatis.metadata.where.item;

import cn.yunbamboos.mybatis.annotation.ForEach;
import cn.yunbamboos.mybatis.metadata.TableInfo;
import cn.yunbamboos.mybatis.metadata.where.TableWhere;
import org.apache.ibatis.scripting.xmltags.ForEachSqlNode;
import org.apache.ibatis.scripting.xmltags.IfSqlNode;
import org.apache.ibatis.scripting.xmltags.MixedSqlNode;
import org.apache.ibatis.scripting.xmltags.SqlNode;
import org.apache.ibatis.scripting.xmltags.StaticTextSqlNode;
import org.apache.ibatis.session.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class TableWhereForEach extends TableWhere {

    private static final Logger logger = LoggerFactory.getLogger(TableWhereForEach.class);

    private final TableInfo tableInfo;
    private final String column;

    private final String item;
    private final String index;
    private final String collection;
    private final String open;
    private final String close;
    private final String separator;

    public TableWhereForEach(TableInfo tableInfo, Field field, ForEach forEach) {
        this.tableInfo = tableInfo;
        this.column = forEach.column();
        this.item = forEach.item();
        this.index = forEach.index();
        this.collection = forEach.collection();
        this.open = forEach.open();
        this.separator = forEach.separator();
        this.close = forEach.close();
    }

    @Override
    public Optional<SqlNode> createSqlNode(Configuration configuration) {
        String notNullTest = getNotNullTest(collection);
        String notEmptyTest = getNotEmptyTest(collection);

        List<SqlNode> contents = new ArrayList<>();
        contents.add(new StaticTextSqlNode("and " + column + " in "));
        contents.add(new ForEachSqlNode(configuration, new StaticTextSqlNode("#{" + item + "}"), CONDITIONS + DOT + collection, true, index, item, open, close, separator));
        return Optional.of(new IfSqlNode(new MixedSqlNode(contents), notNullTest + SPACE + AND + SPACE + notEmptyTest));
    }

}
